package view
{
	import event.GotoReaderEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import model.component.PagesContainer;
	import model.entity.Gamebook;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	
	import skin.renderer.CatalogItemRenderer;
	import skin.renderer.GenresItemRenderer;
	
	import spark.components.Button;
	import spark.components.CheckBox;
	import spark.components.DropDownList;
	import spark.components.List;
	import spark.components.TextInput;
	import spark.components.supportClasses.SkinnableComponent;
	import spark.events.IndexChangeEvent;
	
	//For testing:
	import mx.controls.Alert;
	//
	
	[Event(name="gotoReader", type="event.GotoReaderEvent")]
	public class Catalog extends SkinnableComponent
	{
		
		[SkinPart] public var genresList:List;
		[SkinPart] public var sortBy:DropDownList;
		[SkinPart] public var sortOrder:DropDownList;
		[SkinPart] public var sortBegin:Button;
		[SkinPart] public var searchField:TextInput;
		[SkinPart] public var searchTarget:DropDownList;
		[SkinPart] public var searchBegin:Button;
		[SkinPart] public var nextButton:Button;
		[SkinPart] public var prevButton:Button;
		[SkinPart] public var catalogList:PagesContainer;
		[SkinPart] public var gotoReaderButton:Button;
		[SkinPart] public var resetFilterButton:Button;
		
		[Bindable]
		public var books:ArrayCollection;
		
		public var genresArray:Array = new Array();
		
		
		override protected function getCurrentSkinState():String
		{
			return super.getCurrentSkinState();
		} 
		
		override protected function partAdded(partName:String, instance:Object) : void
		{
			super.partAdded(partName, instance);

			if (instance == genresList)
			{
				genresList.addEventListener("genreCheckboxClicked", handleGenreCheckboxClicked);
			}
			if (instance == resetFilterButton)
			{
				resetFilterButton.addEventListener(MouseEvent.CLICK, handleResetFilterButtonClick);
			}
			if (instance == catalogList)
			{
				catalogList.displayList.addEventListener(MouseEvent.CLICK, handleCatalogListChoice);
			}
			if (instance == sortBegin)
			{
				sortBegin.addEventListener(MouseEvent.CLICK, handleSortByChoice);
			}
			if (instance == searchBegin)
			{
				searchBegin.addEventListener(MouseEvent.CLICK, handleSearchButtonClick);
			}
		}
		
		protected function handleCatalogListChoice(event:Event):void
		{
			var book:Gamebook = books.getItemAt(catalogList.displayList.selectedIndex) as Gamebook;
			catalogList.displayList.selectedItem = -1;
			var file:String = book.file;
			dispatchEvent(new GotoReaderEvent(GotoReaderEvent.GOTOREADER, file));
		}
		
		
		
		protected function handleGenreCheckboxClicked(event:Event):void
		{
			var i:int = 0;
			var hasElem:Boolean = false;
			for (i = 0; i < genresArray.length; i++)
			{
				if (genresArray[i] == genresList.selectedItems.toString()) {
					hasElem = true;
					genresArray.splice(i, 1);
				}
			}
			
			if (!hasElem)
			{
				genresArray.push(genresList.selectedItems.toString())
			}
			
			if (genresArray.length > 0)
			{
				books.filterFunction = processFilter;
			}
			else
			{
				books.filterFunction = null;
			}
			books.refresh();
			//keep refreshPages() !
			catalogList.refreshPages();
		}
		
		private function processFilter(item:Gamebook):Boolean
		{
			var filterGenre:Boolean = true;
			for each (var selectedGenre:Object in genresArray)
			{
				if (item.genre == selectedGenre)
				{
					filterGenre = false;
					break;
				}
			}
			return !filterGenre;
			
		}
		
		protected function handleResetFilterButtonClick(event:MouseEvent):void
		{
			// Code for deselecting all genreCheckboxes - not working!!!
			//genresArray = [];
			// End of code
			
			
			books.filterFunction = null;
			books.refresh();
			//refreshPages() is very important because without it just refreshing books won't work
			catalogList.refreshPages();
		}
		
		override protected function partRemoved(partName:String, instance:Object) : void
		{
			super.partRemoved(partName, instance);
		}
		
		
		protected function handleSortByChoice(event:MouseEvent):void
		{
			var booksSortField:SortField = new SortField();
			booksSortField.name = sortBy.selectedItem.toString().toLowerCase();
			
			
			
			if (sortOrder.selectedItem.toString().toLowerCase() == "descending")
			{
				booksSortField.descending = true;
			}
			else
			{
				booksSortField.descending = false;
			}
			
			var booksSort:Sort = new Sort();
			booksSort.fields = [booksSortField];
			books.sort = booksSort;
			
			
			books.refresh();
			//refreshPages() is very important because without it just refreshing books won't work
			catalogList.refreshPages();
		}
		
		
		protected function handleSearchButtonClick(event:MouseEvent):void
		{
			if (searchField.text != "")
			{
				books.filterFunction = searchFilter;
			}
			else
			{
				if (genresArray.length > 0)
				{
					books.filterFunction = processFilter;
				}
				else
				{
					books.filterFunction = null;
				}
			}
			
			
			books.refresh();
			//refreshPages() is very important because without it just refreshing books won't work
			catalogList.refreshPages();
		}
		
		private function searchFilter(item:Gamebook):Boolean
		{
			var filterSearch:Boolean = true;
			
			// Probably needs reworking!
			if (genresArray.length > 0)
			{
				for each (var selectedGenre:Object in genresArray)
				{
					if (item.genre == selectedGenre)
					{
						if (searchTarget.selectedItem.toString().toLowerCase() == "title")
						{
							if (item.title.toString().toLowerCase().indexOf(searchField.text.toLowerCase()) != -1)
							{
								filterSearch = false;
								break;
							}
						}
						else
						{
							if (item.author.toString().toLowerCase().indexOf(searchField.text.toLowerCase()) != -1)
							{
								filterSearch = false;
								break;
							}
						}
					}	
				}
			}
			else
			{
				if (searchTarget.selectedItem.toString().toLowerCase() == "title")
				{
					if (item.title.toString().toLowerCase().indexOf(searchField.text.toLowerCase()) != -1)
					{
						filterSearch = false;
					}
				}
				else
				{
					if (item.author.toString().toLowerCase().indexOf(searchField.text.toLowerCase()) != -1)
					{
						filterSearch = false;
					}
				}
			}
			
			return !filterSearch;
			
		}
	}
}